<template>
  <div class="min-h-screen bg-gray-100">
    <!-- 侧边栏 -->
    <div class="fixed inset-y-0 left-0 z-50 w-64 bg-white shadow-lg transform transition-transform duration-300 ease-in-out" :class="{ '-translate-x-full': !sidebarOpen, 'translate-x-0': sidebarOpen }">
      <!-- Logo -->
      <div class="flex items-center justify-center h-16 bg-primary">
        <i class="fas fa-book text-white text-2xl mr-2"></i>
        <span class="text-xl font-bold text-white">书香阁管理端</span>
      </div>
      
      <!-- 导航菜单 -->
      <nav class="mt-8">
        <div class="px-4 space-y-2">
          <template v-for="item in menuItems" :key="item.path || item.name">
            <!-- 有子菜单的项目 -->
            <div v-if="item.children" class="space-y-1">
              <button
                @click="toggleSubmenu(item.name)"
                class="w-full flex items-center justify-between px-4 py-3 rounded-lg hover:bg-gray-100 transition-colors"
                :class="isParentMenuActive(item) ? 'bg-primary text-white hover:bg-primary' : 'text-gray-700'"
              >
                <div class="flex items-center">
                  <i :class="item.icon" class="w-5 h-5 mr-3"></i>
                  <span>{{ item.name }}</span>
                </div>
                <i class="fas fa-chevron-down transition-transform duration-200"
                   :class="{ 'rotate-180': isSubmenuOpen(item.name) }"></i>
              </button>
              <!-- 子菜单 -->
              <div v-show="isSubmenuOpen(item.name)" class="ml-6 space-y-1">
                <router-link
                  v-for="child in item.children"
                  :key="child.path"
                  :to="child.path"
                  class="flex items-center px-4 py-2 text-sm text-gray-600 rounded-lg hover:bg-gray-100 transition-colors"
                  :class="{ 'bg-primary text-white hover:bg-primary': $route.path === child.path }"
                >
                  <i :class="child.icon" class="w-4 h-4 mr-3"></i>
                  <span>{{ child.name }}</span>
                </router-link>
              </div>
            </div>
            <!-- 普通菜单项 -->
            <router-link
              v-else
              :to="item.path"
              class="flex items-center px-4 py-3 text-gray-700 rounded-lg hover:bg-gray-100 transition-colors"
              :class="{ 'bg-primary text-white hover:bg-primary': $route.path === item.path }"
            >
              <i :class="item.icon" class="w-5 h-5 mr-3"></i>
              <span>{{ item.name }}</span>
            </router-link>
          </template>
        </div>
      </nav>
    </div>

    <!-- 主内容区域 -->
    <div class="transition-all duration-300 ease-in-out" :class="{ 'ml-64': sidebarOpen, 'ml-0': !sidebarOpen }">
      <!-- 顶部导航栏 -->
      <header class="bg-white shadow-sm border-b border-gray-200">
        <div class="flex items-center justify-between px-6 py-4">
          <div class="flex items-center">
            <button
              @click="toggleSidebar"
              class="p-2 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-primary"
            >
              <i class="fas fa-bars text-xl"></i>
            </button>
            <h1 class="ml-4 text-xl font-semibold text-gray-800">{{ pageTitle }}</h1>
          </div>
          
          <div class="flex items-center space-x-4">
            <!-- 通知 -->
            <button class="relative p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-full">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            
            <!-- 用户菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="ml-2 text-gray-700">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item divided command="settings">设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </header>

      <!-- 页面内容 -->
      <main class="p-6">
        <router-view />
      </main>
    </div>

    <!-- 移动端遮罩 -->
    <div
      v-if="sidebarOpen"
      @click="closeSidebar"
      class="fixed inset-0 z-40 bg-black bg-opacity-50 lg:hidden"
    ></div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const sidebarOpen = ref(true)
const openSubmenus = ref([]) // 展开的子菜单列表
const wasManuallyCollapsed = ref([]) // 记录用户手动收起的菜单

const menuItems = [
  { path: '/admin/dashboard', name: '仪表盘', icon: 'fas fa-tachometer-alt' },
  {
    name: '用户管理',
    icon: 'fas fa-users',
    children: [
      { path: '/admin/users/admin', name: '管理员', icon: 'fas fa-user-shield' },
      { path: '/admin/users/merchant', name: '商家', icon: 'fas fa-store' },
      { path: '/admin/users/regular', name: '普通用户', icon: 'fas fa-user' }
    ]
  },
  { path: '/admin/books', name: '图书管理', icon: 'fas fa-book' },
  { path: '/admin/categories', name: '分类管理', icon: 'fas fa-tags' },
  { path: '/admin/tags', name: '标签管理', icon: 'fas fa-tag' },
  { path: '/admin/bestsellers', name: '畅销管理', icon: 'fas fa-trophy' },
  { path: '/admin/orders', name: '订单管理', icon: 'fas fa-shopping-cart' },
  { path: '/admin/news', name: '新闻管理', icon: 'fas fa-newspaper' },
  { path: '/admin/reviews', name: '评论管理', icon: 'fas fa-comments' }
]

const pageTitle = computed(() => {
  // 先查找普通菜单项
  let currentItem = menuItems.find(item => item.path === route.path)

  // 如果没找到，查找子菜单项
  if (!currentItem) {
    for (const item of menuItems) {
      if (item.children) {
        currentItem = item.children.find(child => child.path === route.path)
        if (currentItem) break
      }
    }
  }

  return currentItem ? currentItem.name : '管理后台'
})

// 检查父菜单是否应该高亮
const isParentMenuActive = (item) => {
  if (!item.children) return false
  return item.children.some(child => route.path === child.path)
}

// 检查子菜单是否应该展开
const isSubmenuOpen = (menuName) => {
  // 优先检查手动控制状态
  if (openSubmenus.value.includes(menuName)) return true

  // 如果没有手动控制，且当前路由匹配子菜单，则自动展开
  const menuItem = menuItems.find(item => item.name === menuName)
  if (menuItem && menuItem.children) {
    const hasActiveChild = menuItem.children.some(child => route.path === child.path)
    // 只有当用户没有手动收起过这个菜单时，才自动展开
    return hasActiveChild && !wasManuallyCollapsed.value.includes(menuName)
  }

  return false
}

const toggleSubmenu = (menuName) => {
  const index = openSubmenus.value.indexOf(menuName)
  const collapsedIndex = wasManuallyCollapsed.value.indexOf(menuName)

  if (index > -1) {
    // 当前是展开状态，用户要收起
    openSubmenus.value.splice(index, 1)
    // 记录用户手动收起了这个菜单
    if (collapsedIndex === -1) {
      wasManuallyCollapsed.value.push(menuName)
    }
  } else {
    // 当前是收起状态，用户要展开
    openSubmenus.value.push(menuName)
    // 移除手动收起的记录
    if (collapsedIndex > -1) {
      wasManuallyCollapsed.value.splice(collapsedIndex, 1)
    }
  }
}

// 监听路由变化，自动展开对应的父菜单
watch(() => route.path, (newPath) => {
  // 找到当前路由对应的父菜单
  for (const item of menuItems) {
    if (item.children) {
      const hasActiveChild = item.children.some(child => child.path === newPath)
      if (hasActiveChild &&
          !openSubmenus.value.includes(item.name) &&
          !wasManuallyCollapsed.value.includes(item.name)) {
        // 只有在用户没有手动收起过的情况下，才自动展开
        openSubmenus.value.push(item.name)
      }
    }
  }
}, { immediate: true })

const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value
}

const closeSidebar = () => {
  sidebarOpen.value = false
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      // 跳转到后台管理专用的个人资料页面
      router.push('/admin/profile')
      break
    case 'settings':
      // 跳转到后台管理专用的设置页面
      router.push('/admin/settings')
      break
    case 'logout':
      userStore.logout()
      router.push('/login')
      break
  }
}

// 响应式处理
const handleResize = () => {
  if (window.innerWidth < 1024) {
    sidebarOpen.value = false
  } else {
    sidebarOpen.value = true
  }
}

onMounted(() => {
  handleResize()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.router-link-active {
  @apply bg-primary text-white;
}
</style>
